import { Howl,Howler } from "howler";

/// 只有播放器功能，没有播放列表
/// 每首歌播放完毕或者error, 通过回调函数自己处理播放切换逻辑。每次需要新建一个播放器实例

console.log(Howler._codecs);

/*
 * 播放器
 * 每次只播放一首歌，完毕/错误后，通过cb通知使用者，播放下一首歌或者继续播放当前歌曲
 * volume: 0.0-1.0
 * rate: 0.5-4.0
 * err_cb: function (error)
 * end_cb: function ()
 */
export class Player {
  constructor(src, volume, rate, method, headers, err_cb, end_cb, seek_cb) {
    // console.log("Player", err_cb, end_cb, seek_cb);
    this._player_id = 0;
    this._player_seek = 0;
    this._player = new Howl({
      src: src,
      volume: volume == null ? 1.0 : volume,
      mute: false,
      html5: true, // 对大文件的加载比较友好
      preload: "metadata", // 提前加载元数据
      autoplay: true, // 默认自动播放
      loop: false,
      rate: rate == null ? 1.0 : rate, // 播放速度, 0.5-4.0
      xhr: {
        withCredentials: false,
        headers: headers,
        method: method == null ? "GET" : method,
      },
      onloaderror: function (id, error) {
        console.log("player onloaderror", id, error);
        if (this._player) this._player.stop();
        if (err_cb) err_cb(error);
      },
      onplayerror: function (id, error) {
        console.log("player onplayerror", id, error);
        if (this._player) this._player.stop();
        if (err_cb) err_cb(error);
      },
      onend: function () {
        console.log("player onend");
        if (this._player) this._player.stop();
        if (end_cb) end_cb();
      },
    });
    this._trigger = setInterval(() => {
      this._player_seek = this._player.seek();
      if (seek_cb) seek_cb(Math.round(this._player_seek));
    }, 1000);
  }
  instance() {
    return this._player;
  }
  seek(){
    return this._player_seek;
  }
  // 控制当前播放
  // play/resume, pause, stop, seek, volume, rate
  ctrl(cmd, val) {
    if (!this._player) return;
    switch (cmd) {
      case "play":
      case "resume":
        if (this._player_id == 0) {
          this._player_id = this._player.play();
        } else {
          this._player.play(this._player_id);
        }
        break;
      case "pause":
        this._player.pause();
        break;
      case "stop":
        this._player.stop();
        this._player_id = 0;
        break;
      case "seek":
        this._player.seek(val);
        break;
      case "volume":
        this._player.volume((val * 1.0) / 100);
        break;
      case "rate":
        this._player.rate(val);
        break;
    }
  }
  destroy() {
    if (!this._player) return;
    if (this._trigger) clearInterval(this._trigger);
    this._player.stop();
    this._player.unload();
  }
}
